package com.jintoufs.web.action.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.UnauthorizedException;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.cosmos.modules.web.utils.ServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;

import java.util.logging.Logger;

/**
 * Created by Administrator on 2015/6/24.
 */
@ControllerAdvice
public class SpringMVCExceptionHandler {
    protected static Log logger = LogFactory.getLog(SpringMVCExceptionHandler.class);

    @ExceptionHandler(value={Exception.class,Error.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String processUnauthenticatedException(NativeWebRequest request,HttpServletResponse response,Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
                .getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf(
                "XMLHttpRequest") > -1))||request.getParameter("blank")!=null) {
            return "/error/500"; //返回一个逻辑视图名
        } else {
            //-- 异步请求以JSON格式返回--
            AjaxMsg ajaxMsg = new AjaxMsg();
            ajaxMsg.setMessage(ex.getMessage()==null?("系统异常："+ex.getClass().getName()):ex.getMessage());
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ServletUtils.renderJson(response, ajaxMsg);

            return null;
        }
    }
    /**
     * 没有权限 异常
     * <p/>
     * 后续根据不同的需求定制即可
     */
    @ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
        return "/error/unauthorized"; //返回一个逻辑视图名
    }
}
